package com.beeasy.hzbpm.bean;

import com.mongodb.client.MongoCollection;
import org.bson.Document;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import static com.beeasy.hzbpm.bean.MongoService.db;

public class Lock {

    public static Map<String, Lock> lockMap = new HashMap<>();
    private static MongoCollection<Document> col = db.getCollection("lock");

    private ReentrantLock lock = new ReentrantLock();
    private String id;
    private Condition condition = lock.newCondition();

    public static Lock getInsLock(String insId){
        synchronized (lockMap){
            Lock lock = lockMap.get(insId);
            if (lock == null) {
               lock = new Lock();
               lock.id = insId;
               lockMap.put(insId, lock);
            }
            return lock;
        }
    }


    public void lock(){
        System.out.println(Thread.currentThread().getName());
        lock.lock();
    }

    public void unlock(){
        lock.unlock();
    }

    public void release(){
        release(id);
    }

    public static void lock(String id){
        getInsLock(id).lock();
    }

    public static void unlock(String id){
        getInsLock(id).unlock();
    }

    public static void release(String id){
        synchronized (lockMap){
            lockMap.remove(id);
        }
    }
}
